﻿using System;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public class ExportModelStateToTempDataAttribute : ModelStateTransferAttribute
	{
		public bool IncludeIfValid { get; set; }

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			if (IncludeIfValid || !filterContext.Controller.ViewData.ModelState.IsValid)
			{
				if (filterContext.Result is RedirectResult
				    || filterContext.Result is RedirectToRouteResult)
				{
					filterContext.Controller.TempData[_key] = filterContext.Controller.ViewData.ModelState;
				}
			}

			base.OnActionExecuted(filterContext);
		}
	}
}